//
//  KLNetworkTools.swift
//  BCWeiBo
//
//  Created by bcmac3 on 16/4/1.
//  Copyright © 2016年 KellenYangs. All rights reserved.
//

import UIKit
import AFNetworking

class KLNetworkTools: AFHTTPSessionManager {
    private static let instance: KLNetworkTools = {
        let urlString = "https://api.weibo.com/"
        let baseURL = NSURL(string: urlString)!
        
        let tools = KLNetworkTools(baseURL: baseURL)
        
        // 设置相应的默认反序列化格式
        tools.responseSerializer.acceptableContentTypes = NSSet(objects: "application/json", "text/json", "text/javascript", "text/plain") as? Set<String>
        
        return tools
    }()
    
    /// 全局访问方法
    class func sharedNetworkTools() -> KLNetworkTools {
        return instance
    }
    
    /**
     发送微博
     
     :param: text            需要发送的正文
     :param: image           需要发送的图片
     :param: successCallback 成功的回调
     :param: errorCallback   失败的回调
     */
    func sendStatus(text: String, image: UIImage?, successCallback: (status: KLStatus)->(), failureCallback: (error: NSError)->())
    {
        var path = "2/statuses/"
        let params = ["access_token":KLUserAccount.loadAccount()!.access_token! , "status": text]
        if image != nil
        {
            // 发送图片微博
            path += "upload.json"
            POST(path, parameters: params, constructingBodyWithBlock: { (formData) -> Void in
                // 1.将数据转换为二进制
                let data = UIImagePNGRepresentation(image!)!
                
                // 2.上传数据
                /*
                第一个参数: 需要上传的二进制数据
                第二个参数: 服务端对应哪个的字段名称
                第三个参数: 文件的名称(在大部分服务器上可以随便写)
                第四个参数: 数据类型, 通用类型application/octet-stream
                */
                formData.appendPartWithFileData(data
                    , name:"pic", fileName:"abc.png", mimeType:"application/octet-stream");
                
                }, success: { (_, JSON) -> Void in
                    successCallback(status: KLStatus(dict: JSON as! [String : AnyObject]))
                }, failure: { (_, error) -> Void in
                    failureCallback(error: error)
            })
        }else
        {
            // 发送文字微博
            path += "update.json"
            POST(path, parameters: params, success: { (_, JSON) -> Void in
                successCallback(status: KLStatus(dict: JSON as! [String : AnyObject]))
                }) { (_, error) -> Void in
                    failureCallback(error: error)
            }
        }
        
    }

}
